 // g++ socket_cli.cpp -lwsock32 -o socket_cli
//#include "stdafx.h"
#include<stdio.h>
#include<tchar.h>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
using namespace std;
 
typedef struct machine_cmd{
double x;
double y;
double z;
double x_v;
double y_v;
double z_v;
} ;
typedef union u_cmd{
machine_cmd mc;
char raw[48];
};
 
// #pragma comment(lib, "ws2_32.lib")
int main(int argc, _TCHAR* argv[])//_tmain,要加＃include <tchar.h>才能用
{
        u_cmd mc_out;

    WSAData wsd;           //初始化信息
    SOCKET soRecv;              //接收SOCKET
    char * pszRecv = NULL; //接收数据的数据缓冲区指针
    int nRet = 0;
    //int i = 0;
    int dwSendSize = 0;
    SOCKADDR_IN siRemote,siLocal;    //远程发送机地址和本机接收机地址
 
    //启动Winsock
    if (WSAStartup(MAKEWORD(2,2),&wsd) != 0) {
        cout << "WSAStartup Error = " << WSAGetLastError() << endl;
        return 0;
    }
 
    //创建socket
    soRecv = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if (soRecv == SOCKET_ERROR) {
        cout << "socket Error = " << WSAGetLastError() << endl;
        return 1;
    }
 
    //设置端口号
    int nPort = 5150;
 
    //int nPort = 1234;
    siLocal.sin_family = AF_INET;
    siLocal.sin_port = htons(nPort);
    siLocal.sin_addr.s_addr = inet_addr("127.0.0.1");
 
    //绑定本地地址到socket
    if (bind(soRecv,(SOCKADDR*)&siLocal,sizeof(siLocal)) == SOCKET_ERROR) {
        cout << "bind Error = " << WSAGetLastError() << endl;
        return 1;
    }
 
    //申请内存
    pszRecv = new char[4096];
    if (pszRecv == NULL) {
        cout << "pszRecv new char Error " << endl;
        return 0;
    }
 
    for (int i = 0; i < 30; i ++){
        dwSendSize = sizeof(siRemote);
        //开始接受数据
        nRet = recvfrom(soRecv,pszRecv,4096,0,(SOCKADDR*)&siRemote,&dwSendSize);
        if (nRet == SOCKET_ERROR) {
            cout << "recvfrom Error " << WSAGetLastError() << endl;
            break;
        }
        else if (nRet == 0) {
            break;
        }
        else{
            memcpy(mc_out.raw,pszRecv,48);
            std::cout<< "X"<< mc_out.mc.x <<" "
            << "y:" << mc_out.mc.y <<" "
            << "z:" << mc_out.mc.z <<" "
             << "x_v:" << mc_out.mc.x_v <<" "
              << "y_v:" << mc_out.mc.y_v <<" "
               << "z_v:" << mc_out.mc.z_v <<" "
            <<std::endl;
            // pszRecv[nRet] = '\0';
            // cout << inet_ntoa(siRemote.sin_addr) << endl
            //     <<pszRecv << endl;
        }
 
    }
    //关闭socket连接
    closesocket(soRecv);
    delete[] pszRecv;
 
    //清理
    WSACleanup();
    system("pause");
    return 0;
}